#include "FilterHelper.h"
#include "NetSIVnPdu.h"
#include "hi_appcomm_log.h"
#include "NetCore.h"
#include "NetVersion.h"
#include "NetCapture.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "NetAudio.h"
#include <system/System.h>
#include "video/Video.h"


extern int g_nCapture;
extern CCapture_List gCapture_List;

#define BITMSK(bit)                (int)(1 << (bit))


typedef struct tagCONFIG_OSDPARAM
{
    uint size; //字体大小,1表示标准倍数，2表示2倍大小  该值取值范围在1到ucZoomAbility之间
    uint index;//用掉一个保留位，表示通道
    uint res[2]; //保留
}CONFIG_OSDPARAM;

typedef struct tagTIMESECTION
{
    //!使能
    int  enable;
    //!开始时间:小时
    int startHour;
    //!开始时间:分钟
    int    startMinute;
    //!开始时间:秒钟
    int    startSecond;
    //!结束时间:小时
    int    endHour;
    //!结束时间:分钟
    int    endMinute;
    //!结束时间:秒钟
    int    endSecond;
}TIMESECTION; 

typedef struct tagVIDEOCOLOR_PARAM
{
	int	nBrightness;		/*!< 亮度	0-100 */
	int	nContrast;			/*!< 对比度	0-100 */
	int	nSaturation;		/*!< 饱和度	0-100 */
	int	nHue;				/*!< 色度	0-100 */
	int	mGain;				/*!< 增益	0-100 第７位置1表示自动增益　*/		
	int	mWhitebalance;		/*此值现在用于光圈基准值*/
}VIDEOCOLOR_PARAM; 



typedef struct {
   int left;
   int top;
   int right;
   int bottom;
}VD_RECT,*VD_PRECT;

//!视频物件结构
typedef struct  tagVIDEO_WIDGET
{
	
	uint rgbaFrontground;		/*!< 物件的前景RGB，和透明度 */	
	uint rgbaBackground;		/*!< 物件的后景RGB，和透明度*/	
	VD_RECT	rcRelativePos;			/*!< 物件边距与整长的比例*8191 */	
	int 	bPreviewBlend;			/*!< 预览叠加 */	
	int 	bEncodeBlend;			/*!< 编码叠加 */
} VIDEO_WIDGET;

#define N_COLOR_SECTION 2

typedef struct tagVIDEOCOLOR
{
	TIMESECTION			TimeSection;		/*!< 时间段 */
	VIDEOCOLOR_PARAM	dstColor;			/*!< 颜色定义 */
	int					iEnable;
}VIDEOCOLOR;
typedef struct tagCONFIG_VIDEOCOLOR
{
	VIDEOCOLOR dstVideoColor[N_COLOR_SECTION];
}CONFIG_VIDEOCOLOR;
typedef struct tagNET_VIDEOCOLOR
{
    int iChannel;
	CONFIG_VIDEOCOLOR stVideoColor;
}NET_VIDEOCOLOR;



typedef struct _NET_DISK_PARTION_INFO_
{
    unsigned char ucUse;         //此分区是否有效
    unsigned char ucPartion;    //分区号；
    unsigned char ucFSType;

    //分区支持的文件系统

    // 0 WFS文件系统  现有最大支持2分区，且分区又约束如下三种方式

    // WFS2分区的话，默认第1分区为快照分区，第2分区为录像分区

    //  如果是WFS 1分区的话，根据ucPartType决定

    //  ucPartType==0，录像分区；ucPartType==1快照分区

    //  此时快照（存储图片）后者录像，设备只能进行一种媒体的存储

    //  WFS文件系统约束只作百分比2分区模式

    // 1 FAT32

    // 2 EXT3

    unsigned char ucPartType;

    //WFS文件系统分区专用 0 录像分区  1快照分区；标准文件系统，不需要，无限制

    uint uiTotalSpace; ///< 总容量，其单位参考ucSpaceType说明

    uint uiRemainSpace; ///< 剩余容量，其单位参考ucSpaceType说明

    unsigned char ucSpaceType;   

    //标识硬盘容量单位，方便比较准确的统计

    //  后4位（7  6 5 4 ） 总大小单位  0 KB，1MB，2GB，3TB

    //  前4位（3 2 1 0） 剩余小单位  0 KB，1MB，2GB，3TB

    unsigned char ucRes[3];//保留

} NET_DISK_PARTION_INFO;

typedef struct _NET_DISK_INFO_
{
    unsigned char ucDiskNo;          //盘符,第几个硬盘 最多255个

    unsigned char ucCurrentUse;     //是否当前使用工作盘

    unsigned char ucLocalStorage;  //本地存储还是远程存储介质 0本地 1远程

    unsigned char ucDiskType;       

    //硬盘介质类型 0 sata硬盘 1，U盘，3 sd卡，4，移动硬盘，5，dvd光盘

    unsigned char ucErrorFlag;      //工作盘错误标志

    unsigned char ucPartMethod;      

    //支持分区模式 

    // 第0位表示是否支持分区 0 不支持 1支持

    //  后七位 按位标识支持分区方式 

    //  第1位 按照百分比分区 0 不支持 1支持

    //   第2位 按照容量分区 MB  0 不支持 1支持

    //   第3位 按照容量分区 GB  0 不支持 1支持

    //   第4位 按照容量分区 TB 0 不支持 1支持

    unsigned char ucSupportPartionMax;         //支持硬盘最大分区个数

    unsigned char ucSupportFileSystem;      

    //支持的文件系统0 WFS 1 FAT32 2 EXT3 安位表示

    uint uiTotalSpace; ///< 总容量，其单位参考ucSpaceType说明

    uint uiRemainSpace; ///< 剩余容量，其单位参考ucSpaceType说明

     unsigned char ucSpaceType;   

    //标识硬盘容量单位，方便比较准确的统计

    //  后4位（7  6 5 4 ） 总大小单位  0 KB，1MB，2GB，3TB

    //  前4位（3 2 1 0） 剩余大小单位  0 KB，1MB，2GB，3TB

    unsigned char ucAttr;       //0 可读写 （默认），1只读， 2 冗余备份
    unsigned char ucRes[2];

    NET_DISK_PARTION_INFO szPartion[4];

    unsigned char ucRes2[64];

} NET_DISK_INFO;

typedef struct  tagDEV_CHANNEL
{
    unsigned short usTotal;  //总通道数目
    unsigned short usIndex;  //第几个通道信息
}DEV_CHANNEL;

typedef struct _Super_User_Auth_List
{
    unsigned int uiFunMask;   //
	/*按位表示支持的功能
	0 : 支持多种机芯设置 
       1:  多种编码类型
       2: 支持设置坏点检查
	*/
    unsigned int uiSensorTypeL;   /*机芯类型掩码低32位*/
    unsigned int uiSensorTypeH;	
    unsigned char ucProfileType;  /* 掩码表示2 hp  1 M   0  Baseline*/
    unsigned char uiReserved[63];
} SUPER_USER_AUTH_LIST, *pSUPER_USER_AUTH_LIST;

typedef struct  tagAUDIO_FORMAT
{
	int		nBitRate;				/*!< 码流kbps*/	
	int		nFrequency;				/*!< 采样频率*/	
#ifdef _FUNC_ADJUST_VOLUME_   //add langzi 音量控制 2010-6-30
	unsigned char ucLAudioVolumn;   //左声道音量
	unsigned char ucRAudioVolumn;   //右声道音量，单声道的设备左右值一样
	unsigned char ucRes[2];
#else
	int		nMaxVolume;				/*!< 最大音量阈值*/
#endif
} AUDIO_FORMAT;

typedef struct  tagVIDEO_FORMAT
{
	int		iCompression;			/*!< 压缩模式 */	
	int		iResolution;			/*!< 分辨率 参照枚举capture_size_t(DVRAPI.H) */	
	int		iBitRateControl;		/*!< 码流控制 参照枚举capture_brc_t(DVRAPI.H) */	
	int		iQuality;				/*!< 码流的画质 档次1-6	*/	
	int		nFPS;					/*!< 帧率值，NTSC/PAL不区分,负数表示多秒一帧*/		
	int		nBitRate;				/*!< 0-4096k,该列表主要由客户端保存，设备只接收实际的码流值而不是下标。*/
	int		iGOP;					/*!< 描述两个I帧之间的间隔时间，2-12 */
} VIDEO_FORMAT;

typedef struct  tagMEDIA_FORMAT
{
	VIDEO_FORMAT vfFormat;			/*!< 视频格式定义 */			
	AUDIO_FORMAT afFormat;			/*!< 音频格式定义 */
	int	bVideoEnable;			/*!< 开启视频编码 */
	int	bAudioEnable;			/*!< 开启音频编码 */	
} MEDIA_FORMAT;
typedef struct tagNET_ENCODE
{
	int  iChannel;
	int iSteamIndex;   
	/*!<码流格式 
	主码流 参考枚举参考ENCODE_TYPE_BY_RECORD ，现有产品默认只有一个主码流，填充为0；
	副码流 参考 ENCODE_TYPE_BY_SUBSTREAM，最多4种子码流，现在产品最多支持一种副码流，填充为0；
	捉图码流 参考 ENCODE_TYPE_BY_SUBSTREAM，最多从4种码流中进行捉图配置
	*/	
	MEDIA_FORMAT dstFmt;		/*!<码流格式 */	

} NET_ENCODE;

typedef struct  tagNET_VIDEO_WIDGET
{
	unsigned short  usChannel;
	unsigned short	 usRes;	
	VIDEO_WIDGET	dstWidget;
} NET_VIDEO_WIDGET;

enum GeneralMsgRetCode
{
    GeneralMsgRetCode_Success = 0, // 无错
    GeneralMsgRetCode_Busy = 1, // 系统忙
    GeneralMsgRetCode_NoAuth = 2, // 无权限
    GeneralMsgRetCode_ConnFull = 3, // 连接满
    GeneralMsgRetCode_IpNotAllowed = 4, // IP 不被容许
};

enum EnLoginResult
{
	EnLoginResult_Succeeded = 0,	// login succeeded
	EnLoginResult_Failed = 1,		 // login failed
	EnLoginResult_Logined = 3,		  // login yet
};
enum EnLoginFailedErrorId
{
	EnLoginFailed_PasswdNotValid = 0, // 密码不正确
	EnLoginFailed_AccountNotValid,// 帐号不存在
	EnLoginFailed_AccountLogined = 3,//已经登录
	EnLoginFailed_AccountLocked,//被锁定
	EnLoginFailed_AccountInBlackList,//黑名单
};




//!查询视频属性信息
typedef struct __sysattr_video_caps
{
    unsigned int iCifCaps;         // 大小
    unsigned int iTypeCaps;        // 编码
    unsigned int iFrameCaps;    // 帧率
    unsigned int iQualityCaps;    // 画质
    unsigned char iCifFrames;    // 每个芯片编码总帧数 单位：cif/s
    unsigned char _iRev_00;        // 保留
    unsigned char _iRev_01;        // 保留
    unsigned char _iRev_02;        // 保留
    unsigned int iReserved_01;    // 保留
    unsigned int iReserved_02;    // 保留
    unsigned int iReserved_03;    // 保留
    unsigned char iStandard;    // 制式
    unsigned char iRev_00;        // 保留
    unsigned char iRev_01;        // 保留
    unsigned char iRev_02;        // 保留
}SYSATTR_VIDEO_CAPS_T;



//区域遮挡
#define COVERNUM 8
#define MARKERNUM 1
typedef struct  tagNET_VIDEO_COVER
{
	unsigned short usChannel;
	unsigned short	 usCoverNum;	/*!< 当前该通道有几个叠加的区域 */
	VIDEO_WIDGET	dstCovers[COVERNUM];
} NET_VIDEO_COVER;

/*
 * 功能说明： 给网络 模块应答指令iRetCode
 * 例子 AckNomoral(c, 0, GeneralMsgRetCode_ConnFull);
 */


void AckNomoral(struct conn *pConnect , unsigned char iLastOpr, unsigned char iRetCode)
{
    //应答
    SIVnPdu * pResp = (struct SIVnPdu *)malloc(sizeof(SIVnPdu));

    if(pResp)
    {
        Net_packetBody(pResp,NULL,0);
        pResp->m_pIpHdr->dvrip_cmd = ACK_INFO_NORMAL;
        pResp->m_pIpHdr->dvrip_p[0] = iLastOpr;
        pResp->m_pIpHdr->dvrip_p[4] = iRetCode;
        
        msghdr_t msghdr;
        memset(&msghdr, 0, sizeof(msghdr));
        msghdr.buf     = (void*)pResp->m_pBuffer;
        msghdr.buf_len = pResp->m_iTotalLen;
        DvrNetSendMsg(pConnect, &msghdr);
         free(pResp);
    }
}



/**********************************************
 * 函数说明：Svc网络模块链接时候使用 用来注册成员
 ***********************************************/

int  RegisterConn(struct conn *c) 
{
	gCapture_List.m_Connect_Number++;		
    if(gCapture_List.m_Connect_Number<50+1)
    {
        
        
    }
    else
    {
    	LOGE("In The AckNomoral \n");
        AckNomoral(c, 0, GeneralMsgRetCode_ConnFull);  //登录人数超过，给网络模块应答超过人数
        return -1;    
    }
	
	
    return 0;
}
/***********************
函数说明：注销链接人员
***********************/
void unRegisterConn(struct conn* c)
{
	if(gCapture_List.m_Connect_Number>0)
	gCapture_List.m_Connect_Number--;	
	NetCapture_DeleteNumber(c);
	Net_AudioSend_DeleteNumber(c);

    
}
/*
 * 函数说明: 子连接请求命令
 */
int OprSubConn(struct conn *pConnect , SIVnPdu* pReqPDU)
{										
	pConnect->iSubConnChn = pReqPDU->m_pIpHdr->dvrip_p[5];
    pConnect->iSubConnType = pReqPDU->m_pIpHdr->dvrip_p[4];
    memcpy((char *)&pConnect->ulConnSequenceFlag,pReqPDU->m_pIpHdr->dvrip_p,4);
    pConnect->iSubConnFlag = 1;
    return 0;

}

typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;

/// 捕获通道类型
enum capture_channel_t {
	CHL_MAIN_T = 0,		///< 主通道	－	主码流1 
	CHL_2END_T = 1,		///< 辅通道	－	出辅码流2 
	CHL_3IRD_T = 2,		///< 辅通道	－	出辅码流3 
	CHL_4RTH_T = 3,		///< 辅通道	－	出辅码流4 
	CHL_JPEG_T = 4,		///< 辅通道	－	出JPEG抓图 
	CHL_FUNCTION_NUM
};

/// 捕获码流控制模式类型
enum capture_brc_t {
	CAPTURE_BRC_CBR,			///< 固定码流。
	CAPTURE_BRC_VBR,			///< 可变码流。
	CAPTURE_BRC_MBR,			///< 混合码流。
	CAPTURE_BRC_NR				///< 枚举的码流控制模式数目。
};

/// 捕获分辨率类型
/// \note更新下面这个结构时，要同步更新Record.cpp里验证编码能力
enum capture_size_t {
	CAPTURE_SIZE_D1=0, ///< 720*576(PAL) 720*480(NTSC)
	CAPTURE_SIZE_HD1, ///< 352*576(PAL) 352*480(NTSC)
	CAPTURE_SIZE_BCIF, ///< 720*288(PAL) 720*240(NTSC)
	CAPTURE_SIZE_CIF, ///< 352*288(PAL) 352*240(NTSC)
	CAPTURE_SIZE_QCIF, ///< 176*144(PAL) 176*120(NTSC)
	CAPTURE_SIZE_VGA, ///< 640*480(PAL) 640*480(NTSC)
	CAPTURE_SIZE_QVGA, ///< 320*240(PAL) 320*240(NTSC)
	CAPTURE_SIZE_SVCD, ///< 480*480(PAL) 480*480(NTSC)
	CAPTURE_SIZE_QQVGA, ///< 160*128(PAL) 160*128(NTSC)
	CAPTURE_SIZE_720P = 9, ///< 1280*720    720p
	CAPTURE_SIZE_1080P = 10, ///< 1920*1080  1080p
	CAPTURE_SIZE_SVGA=11, // <  800*592
	CAPTURE_SIZE_XVGA=12, // <  1024*768    VGA输入编码，2800项目需要
	CAPTURE_SIZE_WXGA=13, // <  1280*800
	CAPTURE_SIZE_SXGA=14, // <  1280*1024  
	CAPTURE_SIZE_WSXGA=15, // <  1600*1024  
	CAPTURE_SIZE_UXGA=16, // <  1600*1200
	CAPTURE_SIZE_WUXGA=17, // <  1920*1200
	CAPTURE_SIZE_1280_960 = 18, // < 1280*960
	CAPTURE_SIZE_300W = 19, //2048*1536
	CAPTURE_SIZE_500W = 20, //2592*1944
	CAPTURE_SIZE_600W = 21, //3072*2048
	CAPTURE_SIZE_800W = 22, //3840*2160
	CAPTURE_SIZE_4K = 23, //4096*2160
	CAPTURE_SIZE_8K = 24, //7680*4320
	CAPTURE_SIZE_400W = 25, //2688*1520
	CAPTURE_SIZE_896_504 = 26, ///< 896*504
	CAPTURE_SIZE_360P = 27, ///< 640*360
	CAPTURE_SIZE_NR = 28 ///< 枚举的图形大小种类的数目。
};
	


/// 捕获压缩格式类型
enum capture_comp_t {
	CAPTURE_COMP_DIVX_MPEG4,	///< DIVX MPEG4。
	CAPTURE_COMP_MS_MPEG4,		///< MS MPEG4。
	CAPTURE_COMP_MPEG2,			///< MPEG2。
	CAPTURE_COMP_MPEG1,			///< MPEG1。
	CAPTURE_COMP_H263,			///< H.263
	CAPTURE_COMP_MJPG,			///< MJPG
	CAPTURE_COMP_FCC_MPEG4,		///< FCC MPEG4
	CAPTURE_COMP_H264,			///< H.264
	CAPTURE_COMP_H265,			///< H.265      
	CAPTURE_COMP_NR				///< 枚举的压缩标准数目。
};

typedef struct tagNET_GENERAL
{ 
    /*!< 按位掩码形式
    0 硬盘满时处理 1覆盖"OverWrite", 0停止"StopRecord" 
    1 是否静音
    2 LCD屏幕自动关闭
    3 是否TV输出
    4 是否VGA输出
    5 是否HDMI输出
    */
    int  iCtrlMask;
     
    /*!<?本机编号:[0,?998]?*/ 
    int iLocalNo;
     
    //!屏保时间(分钟) [0, 120]
    unsigned short usScreenSaveTime;
     
    //!本地菜单自动注销(分钟) [0, 120]
    unsigned short usAutoLogout;
     
    uchar              ucDateFormat;//日期格式/*!< 日期格式:“YYMMDD”, “MMDDYY”, “DDMMYY” */

     uchar              ucDateSprtr;//日期分隔符/*!< 日期分割符:“.”, “-”, “/” */

    uchar               ucTimeFmt;//时间格式/*!< 时间格式:1:"12";    0: "24" */

    uchar ucRes;
    
    /*设备可以支持的制式 ， 第0位 PAL ，第1位 NTSC， 第2位 SECAM*/
    uchar ucSupportVideoFmt;
    
    /*设备使用的制式 ，0 PAL ，1 NTSC， 2 SECAM*/
    uchar ucCurVideoFmt;

    //uchar ucRes1[2];将此保留字节修改，此部分只有在
    uchar ucMenuLayer;//菜单输出 ，0 HDMI，1 VGA，2 TV，说明此操作仅在98系列上支持，对于97设备默认不处理
    uchar ucResolution;//输出分辨率，0:1920*1080 , 1:1280*1024 , 2:1024*768 , 3:800*600
 
    /*设备支持的语言 ， 

    第0位English ，第1位 SimpChinese， 第2位 TradChinese， 第3位 “Italian”,
    4 “Spanish”, 5“Japanese”, 6“Russian”, 7“French”, 8“German”
     ，9 "PORTUGUê"*/

    uint uiSupportLanguage;

     /*设备当前使用的语言 ，

    0 English，1 SimpChinese，2 TradChinese，3“Italian”,4 “Spanish”, 

    5“Japanese”, 6“Russian”, 7“French”, 8“German”,9"PORTUGUê"
    */
    uint uiCurLanguage;

    uint uiRes[3];//保留字节

} NET_GENERAL;
/// 捕获开始类型
enum capture_start_t {
	CAPTURE_START_VIDEO = 1,	///< 视频编码开。
	CAPTURE_START_AUDIO = 2		///< 音频编码开。
};

/// 视频制式类型
enum video_standard_t {
	VIDEO_STANDARD_PAL = 0,	///< PAL制式。
	VIDEO_STANDARD_NTSC,	///< NTSC制式。
	VIDEO_STANDARD_SECAM	///< SECAM制式。
};


/// 捕获设备特性结构
typedef struct CAPTURE_CAPS
{
	/// 支持的压缩标准的掩码，位序号对应枚举类型capture_comp_t的每一个值。
	/// 置1表示支持该枚举值对应的特性，置0表示不支持。
	uint Compression;

	/// 支持的码流控制模式的掩码，位序号对应枚举类型capture_brc_t的每一个值。
	/// 置1表示支持该枚举值对应的特性，置0表示不支持。
	uint BitRateControl;

	/// 支持的图像大小类型的掩码，位序号对应枚举类型capture_size_t的每一个值。
	/// 置1表示支持该枚举值对应的特性，置0表示不支持。
	uint ImageSize;

	/// 支持的媒体类型的掩码，与枚举类型capture_start_t的每一个值相与，得到对应
	/// 的特性。置1表示支持该枚举值对应的特性，置0表示不支持。
	uint Media;

	/// 区域覆盖的支持的块数。
	int CoverBlocks;

	/// 保留。
	//!增加按位表示，
	//!最低位表示:需要通道能力功能, 各通道的能力可能不一样，要调用CaptureGetChnCaps获取
	int Reserved;

	/// 支持最多的标题叠加的个数。
	int	TitleCount;

	/// 是否支持区域覆盖 0-不支持，1-支持实时的区域覆盖， 即设置区域时
	/// 速度较快，可以实时调用， 2-支持非实时的区域覆盖，即设置区域时速度较慢，
	/// 只能在用户确定区域后调用。  
	int	RegionCover;
} CAPTURE_CAPS;

//编码能力集
typedef struct  _ENCODE_CAPS_NET
 {
    uint uiMaxEncodePower;  
    //产品支持的最高编码能力

    ushort usSupportChannel;  
    //- 每块 DSP 支持最多输入视频通道数 
    ushort usChannelSetSync; 
    //- DSP 每通道的最大编码设置是否同步 0-不同步, 1-同步

    //每一通道支持码流情况
    uchar ucVideoStandardMask;
    //视频制式掩码，按位表示设备能够支持的视频制式 0 PAL 1 NTSC
    uchar ucEncodeModeMask; 
    //编码模式掩码，按位表示设备能够支持的编码模式设置 ，0 VBR，1 CBR

    ushort usStreamCap;  
    //按位表示设备支持的多媒体功能，
    //第一位表示支持主码流
    //第二位表示支持辅码流1
    //第三位表示支持jpg抓图，捉图功能另外定义，在此不加入

    uint uiImageSizeMask;   

    //主码流编码掩码 枚举按照capture_size_t 

    uint uiImageSizeMask_Assi[32];     

    //主码流取不同的编码时候，辅码流支持的编码格式，例如, 

    //uiImageSizeMask_Assi【0】表示主码流是CAPTURE_SIZE_D1时，辅码流支持的编码格式，

    //uiImageSizeMask_Assi【1】表示主码流是CAPTURE_SIZE_HD1时，辅码流支持的编码格式。。。

    uchar ucSupportPolicy;  
    //是否支持特殊编码策略 0 不支持 1 支持

    uchar ucCompression;//按位表示，第0位表示是否支持264，第1位表示是否支持svac，第二位表示支持265
	unsigned char   ucRebootType; //如果等于1时，配置主码流HD1，辅码流CIF需要重启设备
    uchar  ucEncoderDetect;  //码流检查
    uchar ucRes[8];   //保留

 } ENCODE_CAPS_NET;

  //!总大小1024
 typedef struct  _ENCODE_CAPS_NET2
 {
	 //!坐标索引为enum capture_size_t，每个分辨率支持的辅助码流(接位表示),
	 //!bit:0 -CHL_2END_T
	 //!bit:1 -CHL_3IRD_T
	 //!bit:2 -CHL_4RTH_T
	 //!bit:3 -CHL_5FTH_T
	 uint ImageSizeMask_Stream[64];
	 uchar rev[768]; //!保留1008个保留位
 }ENCODE_CAPS_NET2;

 ///取出系统支持的码流，以及码流
 typedef struct tagCAPTURE_STREAM_IMAGE
 {
     uint StreamCaps;                        ///< 用channel_t的位来表示支持的功能码流。
     uint CaptureSizeMask[CAPTURE_SIZE_NR];  ///< 每一个值表示对应分辨率支持的辅助码流
 }CAPTURE_STREAM_IMAGE;

 /// 捕获编码能力结构
 typedef struct CAPTURE_DSPINFO 
 {
     unsigned int    nMaxEncodePower;    ///< DSP 支持的最高编码能力。
     unsigned short  nMaxSupportChannel; ///< DSP 支持最多输入视频通道数。
     unsigned short  bChannelMaxSetSync; ///< DSP 每通道的最大编码设置是否同步 0-不同步, 1 -同步。
     unsigned short  nExpandChannel;     ///< DSP 支持的扩展通道数，主要是多路回放使用，目前只是一个
     unsigned short  rev;
 }CAPTURE_DSPINFO, *PCAPTURE_DSPINFO;

 /// 捕获辅助码流支持特性结构
 typedef struct tagCAPTURE_EXT_STREAM
 {
     uint ExtraStream;                       ///< 用channel_t的位来表示支持的功能。
     uint CaptureSizeMask[CAPTURE_SIZE_NR];  ///< 每一个值表示对应分辨率支持的辅助码流。（目前只能用于辅码流）
 }CAPTURE_EXT_STREAM, *pCAPTURE_EXT_STREAM;  

int CaptureGetCaps(CAPTURE_CAPS * pCaps)
{
    if(pCaps == NULL)
    {
        return -1;
    }
    
    pCaps->Reserved = 0;
    pCaps->BitRateControl = (1 << CAPTURE_BRC_CBR) | (1 << CAPTURE_BRC_VBR);
    pCaps->Compression = 1 << CAPTURE_COMP_H264;
	pCaps->ImageSize = 0;
	pCaps->ImageSize |= 1 << CAPTURE_SIZE_VGA;
	pCaps->ImageSize |= 1 << CAPTURE_SIZE_720P;
    //pCaps->ImageSize |= 1 << CAPTURE_SIZE_360P;
    pCaps->Media = CAPTURE_START_VIDEO | CAPTURE_START_AUDIO;
    pCaps->CoverBlocks = 4;
    pCaps->RegionCover = 2;
    pCaps->TitleCount = 6;

    return 0;
}


int CaptureGetExtCaps(CAPTURE_EXT_STREAM *pCaps)
{
    uint captureSizeMask = 0;

    if(pCaps == NULL)
    {
        return -1;
    }
    //pCaps->ExtraStream = (1 << CHL_MAIN_T)|(1 << CHL_2END_T)|(1 << CHL_JPEG_T);
	//pCaps->ExtraStream = (1 << CHL_MAIN_T) | (1 << CHL_2END_T);
	captureSizeMask = (1 <<CAPTURE_SIZE_720P) | (1 <<CAPTURE_SIZE_VGA);
    pCaps->CaptureSizeMask[CAPTURE_SIZE_720P]= captureSizeMask;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_1280_960]= captureSizeMask;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_1080P] = captureSizeMask;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_300W] = captureSizeMask;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_400W] = captureSizeMask;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_500W] = captureSizeMask;
    
    return 0;
}

/*!
    \b Description        :    得到支持的特殊功能，主要是多码流的支持情况\n
    \b Argument            :    CAPTURE_EXT_STREAM* pCaps
    \param    pCaps        :    特殊属性的指针
    \return    非０：成功；０：失败                   
*/
int GetExtCaps(CAPTURE_EXT_STREAM * pCaps)
{
    memset(pCaps, 0, sizeof(CAPTURE_EXT_STREAM));
#ifdef WIN32
    pCaps->ExtraStream = 0;
    pCaps->ExtraStream |= BITMSK(CHL_MAIN_T) | BITMSK(CHL_2END_T) | BITMSK(CHL_JPEG_T);
    pCaps->CaptureSizeMask[CAPTURE_SIZE_CIF] = BITMSK(CAPTURE_SIZE_CIF) | BITMSK(CAPTURE_SIZE_D1) \
        | BITMSK(CAPTURE_SIZE_QCIF);
    pCaps->CaptureSizeMask[CAPTURE_SIZE_BCIF] = BITMSK(CAPTURE_SIZE_CIF) | BITMSK(CAPTURE_SIZE_D1)\
        | BITMSK(CAPTURE_SIZE_QCIF);
    pCaps->CaptureSizeMask[CAPTURE_SIZE_HD1] = BITMSK(CAPTURE_SIZE_CIF) | BITMSK(CAPTURE_SIZE_QCIF) ;
    pCaps->CaptureSizeMask[CAPTURE_SIZE_D1] = BITMSK(CAPTURE_SIZE_CIF) | BITMSK(CAPTURE_SIZE_D1) \
        | BITMSK(CAPTURE_SIZE_QCIF);
#ifndef ENC_SUPPORT_SNAPSHOT
    pCaps->ExtraStream &= ~BITMSK(CHL_JPEG_T);
#endif
    pCaps->ExtraStream |= BITMSK(CHL_JPEG_T);
    return 1;
#else
    int bRet = !CaptureGetExtCaps(pCaps);

#ifndef ENC_SUPPORT_SNAPSHOT
    pCaps->ExtraStream &= ~BITMSK(CHL_JPEG_T);
#endif
    return bRet;
#endif
}

#define DVR_CHN_MAX	1

int CaptureGetDspInfo(CAPTURE_DSPINFO *pDspInfo)
{
    if(pDspInfo == NULL)
    {
        return -1;
    }

    pDspInfo->nMaxSupportChannel = DVR_CHN_MAX;
    pDspInfo->nMaxEncodePower = DVR_CHN_MAX*7680*4320*30;
    pDspInfo->bChannelMaxSetSync = 0;
    pDspInfo->nExpandChannel = 1;

    return 0;
}

/*!
    \b Description        :    获得DSP支持的编码能力\n
    \b Argument            :    CAPTURE_DSPINFO *pDspInfo
    \param    pDspInfo    :    编码能力结构的指针
    \return    非０：成功；０：失败                   
*/
int GetDspInfo(CAPTURE_DSPINFO *pDspInfo)
{
    ///memset(pDspInfo, 0, sizeof(CAPTURE_DSPINFO));
    int bRet = 1;
#ifndef WIN32
    bRet = !CaptureGetDspInfo(pDspInfo);

#ifndef __HuaweiLite__
    assert(pDspInfo->nMaxSupportChannel);
#endif /* __HuaweiLite__ */

#else
    pDspInfo->nMaxEncodePower = 0xffffffff;
    pDspInfo->nMaxEncodePower = 4 * 352 * 288 * 25;
    pDspInfo->nMaxSupportChannel = 4;
    pDspInfo->bChannelMaxSetSync = 1;
#endif

    return bRet;
}

int CaptureGetStreamImageCaps(CAPTURE_STREAM_IMAGE* pCaps)
{
    int j;
    if(pCaps == NULL)
    {
        return -1;
    }
    memset(pCaps, 0, sizeof(CAPTURE_STREAM_IMAGE));
	pCaps->StreamCaps = (1 << CHL_MAIN_T)| (1 << CHL_2END_T) | (1 << CHL_3IRD_T)| (1 << CHL_4RTH_T) | (1 << CHL_JPEG_T );
	//pCaps->StreamCaps = (1 << CHL_MAIN_T) | (1 << CHL_2END_T);
	for( j= 0; j < CHL_FUNCTION_NUM; j++)
    {
        pCaps->CaptureSizeMask[CAPTURE_SIZE_QVGA] |= BITMSK(j);
        pCaps->CaptureSizeMask[CAPTURE_SIZE_VGA] |= BITMSK(j);
        pCaps->CaptureSizeMask[CAPTURE_SIZE_D1] |= BITMSK(j);
		//pCaps->CaptureSizeMask[CAPTURE_SIZE_720P] |= BITMSK(j);
		//pCaps->CaptureSizeMask[CAPTURE_SIZE_360P] |= BITMSK(j);
    }
    return 0;
}


void GetAblility(unsigned char *pData, int *pLen)
{
    int partSize = 0;
    int offset = 0;
    int totalSize = 0;
    ENM_MSG_TYPE enMsyType = 0;

    /* 设备编码能力1 */
    {
        ENCODE_CAPS_NET ability;
        memset( &ability, 0, sizeof(ability) );

        CAPTURE_DSPINFO dspinfo;
        memset(&dspinfo,0,sizeof(CAPTURE_DSPINFO));
        GetDspInfo(&dspinfo);    

        //ability.uiMaxEncodePower = dspinfo.nMaxEncodePower;
		ability.uiMaxEncodePower = dspinfo.nMaxEncodePower;
        ability.usSupportChannel = dspinfo.nMaxSupportChannel;
        ability.usChannelSetSync = dspinfo.bChannelMaxSetSync;

        CAPTURE_CAPS CapsInfo;
        memset(&CapsInfo,0,sizeof(CAPTURE_CAPS));
        CaptureGetCaps(&CapsInfo);

        CAPTURE_EXT_STREAM CapExtInfo;
        memset(&CapExtInfo,0,sizeof(CAPTURE_EXT_STREAM));
        GetExtCaps(&CapExtInfo);
        ability.ucVideoStandardMask = BITMSK(0)|BITMSK(1);
        ability.ucEncodeModeMask = CapsInfo.BitRateControl;


		
		ability.usStreamCap =BITMSK(0)|BITMSK(1); 	//支持主码流和辅码流
        ability.uiImageSizeMask =CapsInfo.ImageSize;

		memcpy(ability.uiImageSizeMask_Assi,CapExtInfo.CaptureSizeMask,CAPTURE_SIZE_NR*sizeof(int));
		//ability.uiImageSizeMask_Assi[0]=(1 << CAPTURE_SIZE_360P) | (1 << CAPTURE_SIZE_720P);
        ability.ucSupportPolicy = 0;     
        //!利用这个保留字，为1表示，修改编码配置分辨率，需要重启      
        //!利堡客户需求，增加主码流的HD1和辅码流CIF，内存不够，采用这种策略
        //!CapsInfo.Reserved按位表示不同功能，第2位表示编码设置是否重启
        ability.ucRes[0]=CapsInfo.Reserved&0xff;
        ability.ucRes[0] |= 0x2;
		
        ability.ucCompression = (1<<0);//按位表示，第0位表示是否支持264，第1位表示是否支持svac，第二位表示支持265
        if(CapsInfo.Compression & (1<<CAPTURE_COMP_H265)){
        ability.ucCompression |= (1<<2);
        }

#ifdef _2761_EXCEPTION_CHK_
        ability.ucEncoderDetect =1;
#endif

        enMsyType = DEV_ABILITY_ENCODE;
        partSize =  sizeof(ENCODE_CAPS_NET);
        memcpy(pData + offset, (unsigned char *)&enMsyType, 4);
        offset += 4;
        memcpy(pData + offset, (unsigned char *)&partSize, 4);
        offset += 4; 
        memcpy(pData + offset, (unsigned char *)&ability, sizeof(ENCODE_CAPS_NET));
        offset += sizeof(ENCODE_CAPS_NET);
    }

    /* 设备编码能力2 */
    {
    	ENCODE_CAPS_NET2* pEncodeCaps = (ENCODE_CAPS_NET2 *)malloc(sizeof(ENCODE_CAPS_NET2));
    	memset( pEncodeCaps, 0, sizeof(ENCODE_CAPS_NET2) );

    	CAPTURE_STREAM_IMAGE tmpCaps;
    	memset(&tmpCaps, 0, sizeof(CAPTURE_STREAM_IMAGE) );

    	CaptureGetStreamImageCaps( &tmpCaps );

    	for( int i = 0; i < CAPTURE_SIZE_NR; i++)
    	{
    		for(int j=CHL_2END_T; j <= CHL_4RTH_T; j++)
    		{
    			if ( tmpCaps.CaptureSizeMask[i] & BITMSK(j) )
    			{
    				pEncodeCaps->ImageSizeMask_Stream[i] |= ( BITMSK(j-CHL_2END_T) );
    			}
    		}

    	}

        enMsyType = DEV_ABILITY_ENCODE2;
        partSize =  sizeof(ENCODE_CAPS_NET2);
        memcpy(pData + offset, (unsigned char *)&enMsyType, 4);
        offset += 4;
        memcpy(pData + offset, (unsigned char *)&partSize, 4);
        offset += 4; 
        memcpy(pData + offset, (unsigned char *)pEncodeCaps, sizeof(ENCODE_CAPS_NET2));
        offset += sizeof(ENCODE_CAPS_NET2);
		free(pEncodeCaps);
    }

    *pLen = offset;
}

int AckAblityTlv(SIVnPdu *pRespPDU)
{
    pRespPDU->m_pIpHdr->dvrip_r1 = 1;

    char *pDataBuf = NULL;
    int dataLen = 0;

    pDataBuf = (char *)malloc(2048);
    if (pDataBuf == NULL) {
        LOGE("malloc failed\n");
        return -1;
    }

    memset(pDataBuf, 0, 2048);
    
    GetAblility(pDataBuf, &dataLen);
	pRespPDU->m_pIpHdr->dvrip_extlen = dataLen;
	pRespPDU->m_pIpHdr->dvrip_hl=8;
	pRespPDU->m_pIpHdr->dvrip_v = 5;
	memset(pRespPDU->m_pIpHdr->dvrip_p, 0, 24);
	pRespPDU->m_pIpHdr->dvrip_p[0]=0x1a;
	Net_packetBody(pRespPDU, (char*)pDataBuf, dataLen);
    free(pDataBuf);
    LOGD("dataLen:%d\n", dataLen);
   
    return 0;
}	

typedef struct __TLV_LIST_INFO
{
	unsigned int m_Type;
	unsigned int m_Length;
	IBTList List;
} Tlv_List_Info;

typedef struct __TLV_Readr
{
	IBTListQueue Head;
}Tlv_Readr_Info;

int QueryDiskCfg(bool *have_tlv_out, unsigned char *buf)
{
	//不使用
	printf(".............QueryDiskCfg...........\n");
	*have_tlv_out = 1;
	int ret = 0 ;
	int iIndex = 0;
	for (iIndex = 0; iIndex < 1; iIndex++)
	{
		NET_DISK_INFO NetDiskInfo;
		memset(&NetDiskInfo,0, sizeof(NET_DISK_INFO));
		
		NetDiskInfo.ucLocalStorage = 0;   
		NetDiskInfo.ucDiskType =0;
		NetDiskInfo.ucPartMethod =0x3 ;
		NetDiskInfo.ucSupportPartionMax = 2;
		NetDiskInfo.ucSupportFileSystem = BITMSK(0);

		NetDiskInfo.ucSpaceType = BITMSK(1)|BITMSK(5);

		uint uidriver_type = 0;      
		NetDiskInfo.ucAttr = 0 ;
		int iTotal = 0,iRemain = 0;
		

		//int ret = g_DriverManager.GetDriverInfo(iIndex, 0, &drivinfor);
			NetDiskInfo.ucDiskNo = iIndex;//drivinfor.index;
			NetDiskInfo.ucCurrentUse =  1;//drivinfor.is_current;
			NetDiskInfo.ucErrorFlag = 0;
	
			NetDiskInfo.uiTotalSpace = (100)/BITMSK(10);
		//	printf("uiTotalSpace:%f",NetDiskInfo.uiTotalSpace);
			NetDiskInfo.ucSpaceType = 2<<4;

			NetDiskInfo.uiRemainSpace = (55 )/BITMSK(10);
			//printf("uiRemainSpace:%f",NetDiskInfo.uiRemainSpace);
			NetDiskInfo.ucSpaceType |=2;

			//&NetDiskInfo,sizeof(NET_DISK_INFO)
		//memcpy(buf)
			unsigned char *buffer =(unsigned char *) malloc(sizeof(NET_DISK_INFO));
			memcpy(buf+8, (unsigned char *)&NetDiskInfo, sizeof(NET_DISK_INFO));
			unsigned int outLength = sizeof(NET_DISK_INFO);
			memcpy(buf + 4, (unsigned char *)&outLength, 4);//额外长度
	}

    return 0;
}

#define CHANNEL_NAME_SIZE        64
typedef struct _ChannelName_
{
    int iChannel;
    char strChannelName[CHANNEL_NAME_SIZE]; 
}CHANNEL_NAME;
int QueryEncodeCfg(bool *have_tlv_out, int s_total_Length, unsigned char *buf,unsigned char *outbuf,unsigned int *outLength)
{
	//送入buf已经malloc了4096
	//Length 输出总长度
	//通道猜测为1
	//一共5个  存在buffer拿出来压入
	//首先解析前面buf 的数据拿出通道
	unsigned int Total_Length = 0;
	//STlv Com_STlv[10] = {0};
	unsigned char *tmp_comm_buf[10] = {0};//10个数据
	unsigned int tmp_comm_Length[10] = {0};
	unsigned int tmp_com_Length = 0;
	int iChn = 0,iTotal = 0;
	unsigned int tmp_len = 0;
	Total_Length =s_total_Length;
	//printf("Total_Length is %d \n", Total_Length);
	//解析buf
	DEV_CHANNEL* pChannel = buf+DVRIP_HEAD_T_SIZE+16;//拿第一个BUF数据
	
	 if( pChannel->usIndex < pChannel->usTotal )
	{
		iChn = pChannel->usIndex;
		iTotal = iChn +1;
	}
	else
	{
		iChn = 0;
		iTotal = pChannel->usTotal;
	}
	//printf("buf + DVRIP_HEAD_T_SIZE +8 is %02X \n", *(buf + DVRIP_HEAD_T_SIZE + 8));
	//开始解析数据
	unsigned int temp_Type=0;
	unsigned int temp_Length = 0;
	VIDEO_STREAM_ATTR_S pstStreamAttr = {0};
	VideoGetOpsHandle()->get_resolution(0, &pstStreamAttr);
	int Stream_Type = 0;
	if(pstStreamAttr.width==1280)
	{
		Stream_Type = 1;
	}
	else if(pstStreamAttr.width==640)
	{
		Stream_Type = 2;
	}
	while(tmp_len<Total_Length)
	{
		//一个个拿出类型
		memcpy(&temp_Type, buf + DVRIP_HEAD_T_SIZE +8+ tmp_len, 4);//   DVRIP_HEAD+MSG+LEN +MSG+LEN+BUF 拿出MSG
		memcpy(&temp_Length, buf + DVRIP_HEAD_T_SIZE + 8+tmp_len+4, 4);//Len长度
		//解析类型
		if(temp_Type==ENCODE_CHANNEL_NAME_TYPE)
		{
			int i;
			unsigned int ChannelLength = 0;
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(CHANNEL_NAME)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(CHANNEL_NAME))) + 8;

			for( i = iChn; i < iTotal; i++ )
            {
                CHANNEL_NAME ChannelName;
                memset(&ChannelName,0,sizeof(CHANNEL_NAME));        
                ChannelName.iChannel = i;
				sprintf(ChannelName.strChannelName, "channel_%d", i);
				//压入BUF
				memcpy((tmp_comm_buf[tmp_com_Length]+8+ChannelLength), (unsigned char *)&ChannelName, sizeof(CHANNEL_NAME));
				ChannelLength += sizeof(CHANNEL_NAME);
            }
			memcpy((tmp_comm_buf[tmp_com_Length]), (unsigned char *)&temp_Type, 4);
			memcpy((tmp_comm_buf[tmp_com_Length] + 4), (unsigned char *)&ChannelLength, 4);
			tmp_com_Length++;
		}
		else if(temp_Type==ENCODE_MAIN_STREAM_TYPE)
		{
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_ENCODE)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_ENCODE))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_ENCODE EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_ENCODE));
				EncodeCfg.iChannel = i;
				EncodeCfg.iSteamIndex = i;
				EncodeCfg.dstFmt.bVideoEnable = 1;
				EncodeCfg.dstFmt.vfFormat.iCompression =CAPTURE_COMP_H264 ;  	//压缩类型
				if(Stream_Type==2)
				{
				EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_VGA;		//码流控制
				}
				else
				{
					EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_720P;		//码流控制
				}
				//只显示720P和360P
				EncodeCfg.dstFmt.vfFormat.iBitRateControl = CAPTURE_BRC_CBR;	//固定码率
				EncodeCfg.dstFmt.vfFormat.iQuality = 3;
				EncodeCfg.dstFmt.vfFormat.nFPS = 15;
				EncodeCfg.dstFmt.vfFormat.nBitRate = 1024;
				EncodeCfg.dstFmt.vfFormat.iGOP = 6;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_ENCODE));
				MAIN_STREAM_Length += sizeof(NET_ENCODE);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}
		else if( temp_Type == ENCODE_SUB_STREAM_TYPE
        		|| temp_Type == ENCODE_3IRD_STREAM_TYPE
        		|| temp_Type == ENCODE_4RTH_STREAM_TYPE
        		|| temp_Type == ENCODE_5FTH_STREAM_TYPE )
		{
				int stream = 0;
				if(temp_Type == ENCODE_SUB_STREAM_TYPE )
        	{
        		stream = 0;
        	}
        	else if(temp_Type == ENCODE_3IRD_STREAM_TYPE )
        	{
        		stream = 1;
        	}
        	else if( temp_Type == ENCODE_4RTH_STREAM_TYPE )
			{
        		stream = 2;
			}
        	else if( temp_Type == ENCODE_5FTH_STREAM_TYPE )
			{
        		stream = 3;
			}

        	if( stream >= 1 )
        	{
				tmp_len += 8 + temp_Length;//更新指针位置
        		continue;
        	}
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_ENCODE)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_ENCODE))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_ENCODE EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_ENCODE));
				EncodeCfg.iChannel = i;
				EncodeCfg.iSteamIndex = i;
				EncodeCfg.dstFmt.bVideoEnable = 1;
				EncodeCfg.dstFmt.vfFormat.iCompression =CAPTURE_COMP_H264 ;  	//压缩类型
				if(Stream_Type==2)
				{
				EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_VGA;		//码流控制
				}
				else
				{
					EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_720P;		//码流控制
				}
				EncodeCfg.dstFmt.vfFormat.iBitRateControl = CAPTURE_BRC_CBR;	//固定码率
				EncodeCfg.dstFmt.vfFormat.iQuality = 3;
				EncodeCfg.dstFmt.vfFormat.nFPS = 15;
				EncodeCfg.dstFmt.vfFormat.nBitRate = 1048;
				EncodeCfg.dstFmt.vfFormat.iGOP = 6;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_ENCODE));
				MAIN_STREAM_Length += sizeof(NET_ENCODE);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}
		else if( temp_Type == ENCODE_SNAP_STREAM_TYPE)
		{
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_ENCODE)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_ENCODE))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_ENCODE EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_ENCODE));
				EncodeCfg.iChannel = i;
				EncodeCfg.iSteamIndex = i;
				EncodeCfg.dstFmt.bVideoEnable = 1;
				EncodeCfg.dstFmt.vfFormat.iCompression =CAPTURE_COMP_H264 ;  	//压缩类型
				//EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_720P;		//码流控制
				if(Stream_Type==2)
				{
				EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_VGA;		//码流控制
				}
				else
				{
					EncodeCfg.dstFmt.vfFormat.iResolution = CAPTURE_SIZE_720P;		//码流控制
				}
				EncodeCfg.dstFmt.vfFormat.iBitRateControl = CAPTURE_BRC_CBR;	//固定码率
				EncodeCfg.dstFmt.vfFormat.iQuality = 3;
				EncodeCfg.dstFmt.vfFormat.nFPS = 15;
				EncodeCfg.dstFmt.vfFormat.nBitRate = 1048;
				EncodeCfg.dstFmt.vfFormat.iGOP = 6;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_ENCODE));
				MAIN_STREAM_Length += sizeof(NET_ENCODE);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);


			tmp_com_Length++;
		}	
		else if( temp_Type == ENCODE_COLOR_TYPE)
		{
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_VIDEOCOLOR)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_VIDEOCOLOR))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_VIDEOCOLOR EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_VIDEOCOLOR));
				EncodeCfg.iChannel = i;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_VIDEOCOLOR));
				MAIN_STREAM_Length += sizeof(NET_VIDEOCOLOR);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}		
		else if(temp_Type == ENCODE_COVER_TYPE)   
        {
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_VIDEO_COVER)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_VIDEO_COVER))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_VIDEO_COVER EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_VIDEO_COVER));
				EncodeCfg.usChannel = i;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_VIDEO_COVER));
				MAIN_STREAM_Length += sizeof(NET_VIDEO_COVER);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}	
		else if( temp_Type == ENCODE_TIMEOSD_TYPE)
        {

			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_VIDEO_WIDGET)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_VIDEO_WIDGET))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_VIDEO_WIDGET EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_VIDEO_WIDGET));
				EncodeCfg.usChannel = i;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_VIDEO_WIDGET));
				MAIN_STREAM_Length += sizeof(NET_VIDEO_WIDGET);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}
		else if(temp_Type == ENCODE_TITLEOSD_TYPE)
        {
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(NET_VIDEO_WIDGET)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(NET_VIDEO_WIDGET))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				NET_VIDEO_WIDGET EncodeCfg;
                memset(&EncodeCfg,0,sizeof(NET_VIDEO_WIDGET));
				EncodeCfg.usChannel = i;
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(NET_VIDEO_WIDGET));
				MAIN_STREAM_Length += sizeof(NET_VIDEO_WIDGET);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}
		else if(temp_Type == ENCODE_OSD_SIZE)
        {
			tmp_comm_buf[tmp_com_Length] = (unsigned char *)malloc((iTotal-iChn)*((sizeof(CONFIG_OSDPARAM)))+8);
			tmp_comm_Length[tmp_com_Length] = (iTotal - iChn) * ((sizeof(CONFIG_OSDPARAM))) + 8;
			unsigned int MAIN_STREAM_Length = 0;
			int i = 0;
			for( i = iChn; i < iTotal; i++ )
			{
				CONFIG_OSDPARAM EncodeCfg;
                memset(&EncodeCfg,0,sizeof(CONFIG_OSDPARAM));
				memcpy((tmp_comm_buf[tmp_com_Length]+8+MAIN_STREAM_Length), (unsigned char *)&EncodeCfg, sizeof(CONFIG_OSDPARAM));
				MAIN_STREAM_Length += sizeof(CONFIG_OSDPARAM);
			}
			memcpy(tmp_comm_buf[tmp_com_Length],(unsigned char *)&temp_Type, 4);
			memcpy(tmp_comm_buf[tmp_com_Length]+4,(unsigned char *)&MAIN_STREAM_Length, 4);
			tmp_com_Length++;
		}
		tmp_len += 8 + temp_Length;//更新指针位置
	}
	int i = 0;
	unsigned int all_Length = 0;
	for (i = 0; i < 10;i++)
	{//取出数组中有数据的指针
		if(tmp_comm_buf[i])//存在
		{	//第一次遍历，不弹掉数据
			//所有buf拿出
			//数据压入总buf中
			//free(tmp_comm_buf[i]);//取完释放数据
			memcpy(outbuf+ all_Length, tmp_comm_buf[i], tmp_comm_Length[i]);//将包组合发出
			all_Length += tmp_comm_Length[i];
		}
	}
	*outLength = all_Length;
	//memcpy(outbuf + 4, (unsigned char *)&all_Length, 4);
}

int OprGetSystemConfig(unsigned char *buf)
{
	NET_GENERAL NetGenCfg;
	unsigned int buf_Length = sizeof(NET_GENERAL);
	memset(&NetGenCfg,0,sizeof(NET_GENERAL));
	NetGenCfg.ucCurVideoFmt = 1;
	NetGenCfg.ucSupportVideoFmt =1;
	NetGenCfg.ucResolution = 3;
	memcpy(buf + 8, (unsigned char *)&NetGenCfg, sizeof(NET_GENERAL));
	memcpy(buf + 4, (unsigned char *)&buf_Length, 4);
}

int OprConfig(bool bGet, SIVnPdu* pReqPDU, SIVnPdu** pRespPDU)
{
	LOGD(".....OprConfig....\n");
	unsigned int tmp_len = 0;		//已经读取的长度
	unsigned int total_Length = 0;	//总长度
	int have_tlv_out = 0;
	if (!pReqPDU)
    {
        return -1;
    }

	
	total_Length = pReqPDU->m_pIpHdr->dvrip_extlen;
	printf("OprConfig total_Length is %d \n", total_Length);
	//应答
    SIVnPdu* pRspPdu = NULL;
    
    SIVnPdu_Init(&pRspPdu);

    *pRespPDU = pRspPdu;

	unsigned char *buf  = (unsigned char *)malloc(2048); //组包数据包
	unsigned char *buf2 = (unsigned char *)malloc(2048);
	unsigned char *buffer = (unsigned char *)malloc(4096);
	unsigned int buffer_Length = 0;
	unsigned int buf_outLength = 0;
	if(!buf)
	{
		SIVnPdu_Destory(&pRspPdu);
		return -1;
	}//buf申请不到
	memset(buf, 0, 2048);
	memset(buf2, 0, 2048);
	memset(buffer, 0, 4096);
	//unsigned char *pack_buf[20] = {0};
	//unsigned int Length[20] = {0};
	//unsigned int pack_buf_point = 0;
	//Tlv_Readr_Info Tlv_Readr;
	//IBT_List_QueueInit(&(Tlv_Readr.Head));
	unsigned int m_Type = 0;
	unsigned int Length = 0;
	int i = 0;
	while(tmp_len<total_Length)
	{ //还没拿完所有数据
		//Tlv_List_Info *New_List = (Tlv_List_Info *)malloc(sizeof(Tlv_List_Info));
		//拿出成员中的类型和长度
		unsigned char *p = pReqPDU->m_pBuffer+DVRIP_HEAD_T_SIZE+tmp_len;//拿出数据buf
		memcpy(&m_Type, p, 4);//前4个字节为MSG_Type
		if(m_Type&0x80000000)
		{//存在嵌套
			m_Type =m_Type- 0x80000000;
		}
		memcpy(&Length, p + 4, 4);
		printf("[%d]m_Type is %d \n",i,m_Type);
		i++;
		tmp_len += (Length+8);//加上MsgType和Length
		switch(m_Type)
		{
			case DEV_SYSTEM_INFO_GENERAL:
				OprGetSystemConfig(buf2);
				memcpy(buf2, (unsigned char *)&m_Type, 4);
				have_tlv_out = 1;
				break;
			/*case DEV_SYSTEM_INFO_DISK_DRIVER:
				QueryDiskCfg(&have_tlv_out, buf);
				have_tlv_out = 1;
				memcpy(buf, (unsigned char *)&m_Type, 4);
				//pack_buf_point++;
				break;*/
			case DEV_CHANNEL_ENCODE_TYPE:
				QueryEncodeCfg(&have_tlv_out, total_Length, pReqPDU->m_pBuffer,buf,&buf_outLength);
				have_tlv_out = 1;
				//memcpy(buf, (unsigned char *)&m_Type, 4);
				//pack_buf_point++;
				break;
			default:
				break;
		}

	}
	unsigned int tt_test_length = 0;
	if(have_tlv_out)
	{//发送buf
		unsigned int Test_Type = 400;
		unsigned int Buf_Length = 0;

		//memcpy(&Buf_Length, buf + 4, 4);
		//Buf_Length += 8;
		memcpy(buffer + 8, buf, buf_outLength);
		buffer_Length += buf_outLength;
		
		memcpy(&Buf_Length, buf2 + 4, 4);
		Buf_Length += 8;
		memcpy(buffer + 8+buffer_Length, buf2, Buf_Length);
		buffer_Length += Buf_Length;
		tt_test_length=buffer_Length+8;
		memcpy(buffer + 4, (unsigned char *)&buf_outLength, 4);
		Test_Type = Test_Type | 0x80000000;
		memcpy(buffer, (unsigned char *)&Test_Type, 4);
		Net_packetBody(pRspPdu,buffer,tt_test_length);
		printf("buffer_Length is %d \n", buffer_Length);
		printf("buf_outLength is %d \n", buf_outLength);
		printf("tt_test_length is %d \n", tt_test_length);
	}
	pRspPdu->m_pIpHdr->dvrip_cmd = ACK_REQ_SYSTEM_CONFIG;
    pRspPdu->m_pIpHdr->dvrip_p[0] = 0;
	pRspPdu->m_pIpHdr->dvrip_v = 5;
	pRspPdu->m_pIpHdr->dvrip_hl = 8;
	pRspPdu->m_pIpHdr->dvrip_extlen = buffer_Length;
	free(buffer);
	free(buf2);
	free(buf);//用完数据 释放掉
	return 0;
}


int FaceTool_SetQulity(unsigned int eCodeMode) //设置分辨率
{
	int Ret 		 = 0;
    uint8_t channel = 0;
    uint32_t BitRate;
    VIDEO_STREAM_ATTR_S stStreamAttr;
	//set  videocfg to bsp
	//save videocfg to cfgfile
	//int codec = RT_CODEC_H264;
	//int colorDepth = B1_VIDEO_COLORDEPTH;
	//int framerate = B1_VIDEO_FPS;
	//int frameInterval = B1_VIDEO_GOP;
    //int width = B1_VIDEO_HD_WIDTH;
   // int height = B1_VIDEO_HD_HEIGHT;
	int codec = 0x34363248;//暂时填死
	int colorDepth = 24;
	int framerate = 15;
	int frameInterval = 15*2;
	int width = 1280;
	int height = 720;
	switch(eCodeMode)
	{
		case CAPTURE_SIZE_720P:
			printf("Fatool Set 720\n");			
			BitRate = 800;//暂时写死
			width  = 1280;
			height = 720;
			break;
		case CAPTURE_SIZE_VGA:
			printf("Fatool Set 360P\n");			
			BitRate = 256;//暂时写死
			width  = 640;
			height = 360;
			break;
		default:
			Ret = -1;
			break;
	}

    memset(&stStreamAttr, 0, sizeof(stStreamAttr));
    stStreamAttr.bitrate = BitRate;
    stStreamAttr.width = width;
    stStreamAttr.height = height;
    stStreamAttr.framerate = framerate;

	Ret = VideoGetOpsHandle()->set_resolution_without_config(0, stStreamAttr);
	if (Ret < 0) {
        LOGE("set_resolution chn:%d failed\n", channel);
        return -1;
	}

    /*
        设置配置
     */
    char temp_widht[64] = {0};
    char temp_hight[64] = {0};
    snprintf(temp_widht, sizeof(temp_widht), "%d",width);
    snprintf(temp_hight, sizeof(temp_hight), "%d",height);
    /*
    ConfigSetEnv(ENV_SOFTWARE_TOKEN, ENV_SOFTWARE_KEY_VIDEO_HEIGHT, temp_hight);
    ConfigSetEnv(ENV_SOFTWARE_TOKEN, ENV_SOFTWARE_KEY_VIDEO_WIDHT, temp_widht);
    ConfigSave();
    */

    return 0;

}


int setOprConfig(SIVnPdu *pReqPDU)
{
	//解析下buf
	const char *read_buf=pReqPDU->m_pBuffer+DVRIP_HEAD_T_SIZE+8;//跳过32头，跳过嵌套MSG
	//解析buf 
	//设置主通道分辨率 
	//解析buf进行设置
	//解析m_pBuffer
	//轮询buf直到mtype为主编码
	unsigned int m_type=0;
	unsigned int m_Length = 0;
	unsigned int m_Len = 0;//长度
	unsigned int m_totalLength = pReqPDU->m_pIpHdr->dvrip_extlen;
	//拿出前面的Channel
	unsigned int iChn = 0;
	unsigned int iTotal = 0;
	
	DEV_CHANNEL* pChannel = pReqPDU->m_pBuffer+DVRIP_HEAD_T_SIZE+16;//拿第一个BUF数据
	if( pChannel->usIndex < pChannel->usTotal )
	{
		iChn = pChannel->usIndex;
		iTotal = iChn +1;
	}
	else
	{
		iChn = 0;
		iTotal = pChannel->usTotal;
	}

	if(m_Len<m_totalLength)
	{
		memcpy((unsigned char *)&m_type, read_buf+m_Len, 4);
		memcpy((unsigned char *)&m_Length, read_buf + m_Len + 4, 4);//扣出长度
		//开始判断类型
		if(m_type==ENCODE_MAIN_STREAM_TYPE)
		{  	//类型
			//开始拿出数据
			LOGD("....setOprConfig ENCODE_MAIN_STREAM_TYPE...\n");
			int temp_iResolution = 0;
			//此时长度m_Length
			//读出数据的分辨率
			NET_ENCODE *EncodeCfg=read_buf+m_Len+8;//拿出数据
			temp_iResolution = EncodeCfg->dstFmt.vfFormat.iResolution;
			printf("......temp_iResolution is %d.....\n", temp_iResolution);
			switch(temp_iResolution)
			{
				case CAPTURE_SIZE_720P:
				//720P
				FaceTool_SetQulity(CAPTURE_SIZE_720P);
				break;
				
				case CAPTURE_SIZE_VGA:
				//360P
				FaceTool_SetQulity(CAPTURE_SIZE_VGA);
				break;
				default :
					LOGD("Bell has no this Format \n");
					break;
			}

		}
		m_Len += m_Length + 8;//更新指针
	}



}

int GetConfig(SIVnPdu *pReqPDU, SIVnPdu **pRespPDU)
{
	OprConfig(true, pReqPDU, pRespPDU);
}

int SetConfig(SIVnPdu *pReqPDU, SIVnPdu **pRespPDU)
{
	//该包不回复
	SIVnPdu *pResp;
	SIVnPdu_Init(&pResp);
	if(pResp==NULL)
		return -1;//申请不到内存
	setOprConfig(pReqPDU);//直接设置 反馈回上述设置包中
	Net_packetBody(pResp,NULL,0);
	pResp->m_pIpHdr->dvrip_cmd=0x01;
	pResp->m_pIpHdr->dvrip_v = 5;
	pResp->m_pIpHdr->dvrip_hl = 8;
	*pRespPDU = pResp;
}






/*!
    \b Description        :    查询系统信息\n
*/
int QuerySysInfo(SIVnPdu *pReqPDU, SIVnPdu **pRespPDU)
{
    if (!pReqPDU)
    {
        return -1;
    }    
    //应答
    SIVnPdu* pRspPdu = NULL;
    
    SIVnPdu_Init(&pRspPdu);

    *pRespPDU = pRspPdu;

    LOGD("dvrip_p[0] = 0x%x\n", pReqPDU->m_pIpHdr->dvrip_p[0]);
    
    switch(pReqPDU->m_pIpHdr->dvrip_p[0] )
    {
        /*设置属性信息*/
        case 0:
        {
            break;
        }        
        case 0x01:  /*设备属性信息*/
            break;
        //!查询视频属性
        case 0x04:
        {
            SYSATTR_VIDEO_CAPS_T VideoInfo;
            memset(&VideoInfo, 0, sizeof(VideoInfo));

            CAPTURE_CAPS tmpCapCaps;
            memset((void*)&tmpCapCaps,0,sizeof(CAPTURE_CAPS));
            CaptureGetCaps(&tmpCapCaps);

            VideoInfo.iCifCaps    = tmpCapCaps.ImageSize;
            VideoInfo.iTypeCaps   = tmpCapCaps.Compression;
            VideoInfo.iFrameCaps  = 0xff;
            VideoInfo.iQualityCaps= 0x3f;
            VideoInfo.iCifFrames  = 100;//25*4
            VideoInfo.iStandard   = VIDEO_STANDARD_NTSC;
            Net_packetBody(pRspPdu, (char *) &VideoInfo, sizeof(SYSATTR_VIDEO_CAPS_T));
            break;
        }        
        case 0x05:
        case 0x09:
        case 0x0e:
        //!查询系统语言集信息
        case 0x14:
        case 0x1a://设备功能集
            LOGD("AckAblityTlv...\n");
			if( pReqPDU->m_pIpHdr->dvrip_r1 == 1 )
            AckAblityTlv(pRspPdu);
			else
			{
				const char *sendbuf = "AutoMaintain:1:Reboot,DeleteFiles";
				Net_packetBody(pRspPdu, (char*)sendbuf, strlen(sendbuf));
			}
            break;
        case 0x1d:
        case 0x1e:   /* 查询网络状态信息，如登录了哪些用户*/
            break;
        default:
        {
            LOGD("dvrip_p[0] = 0x%x\n", pReqPDU->m_pIpHdr->dvrip_p[0]);
            Net_packetBody(pRspPdu,NULL,0);
            pRspPdu->m_pIpHdr->dvrip_p[8] = 2;
            break;
        }
        
    }
       
    pRspPdu->m_pIpHdr->dvrip_cmd = ACK_INFO_SYSTM;
    pRspPdu->m_pIpHdr->dvrip_p[0] = pReqPDU->m_pIpHdr->dvrip_p[0] ;

    return 0;
}






/*****************************
 * 函数说明:接收链接命令处理
 *****************************/

int MsgProcess(struct conn *pConnect, char *buf, int len)
{
		
		SIVnPdu *pReq=0;
		SIVnPdu_Init(&pReq);
		if(pReq&&Net_ParseBody(pReq,buf,len))
		{
			LOGD("The Net Cmd is %x ",pReq->m_pIpHdr->dvrip_cmd);//取出命令
			SIVnPdu *pResp=0;
			switch(pReq->m_pIpHdr->dvrip_cmd)
			{
						 case REQ_USER_LOGIN:
			            {
								LOGD ("cmd [REQ_USER_LOGIN] \n");								
				                if(gCapture_List.m_Connect_Number> 50)
				                {	
				                	
				                	SIVnPdu_Init(&pResp);
				                  
				                    if(pResp) 
				                    {
				                        Net_packetBody(pResp,NULL,0);//使用默认参数NULL,0
				                        pResp->m_pIpHdr->dvrip_cmd = ACK_USER_LOGIN;    
				                        pResp->m_pIpHdr->dvrip_p[0] = EnLoginResult_Failed;
				                        pResp->m_pIpHdr->dvrip_p[1] = 2;    //其他情况，协议未定义
				                    }
				                  
				                }
				                else
				                {	
				                	
				                    RegQuest(pConnect,pReq,&pResp);  //处理登录
				                }
			                break;
			               
			            }
			            case REQ_STAT_QUERY:
			            {
			            	 	SIVnPdu_Init(&pResp);
					            if(pResp)
					            {
					            	Net_packetBody(pResp,NULL,0);//使用默认参数NULL,0
					                pResp->m_pIpHdr->dvrip_cmd = ACK_STAT_QUERY;
					            }
								break;
					     }
						case REQ_SUB_CONN:
						{
							//LOGD ("[%s][%d] cmd [REQ_SUB_CONN]\n", __FILE__, __LINE__);
								OprSubConn(pConnect,pReq);
				                break;
						}
						case REQ_CHAN_SWTCH:
						{
							Capture_FilterCallback(pConnect,pReq->m_pIpHdr);
								break;
						}
						case REQ_AUDIO_DATA:
           			    case ACK_REQ_AUDIO_DATA:
           			    {
							Audio_FilterCallback(pConnect,pReq->m_pIpHdr);
							break;
           			    }
                        case REQ_INFO_SYSTM:
                        {
                            LOGD("REQ_INFO_SYSTM...\n");
                            QuerySysInfo(pReq, &pResp);
                            break;
                        }

						case REQ_SYSTEM_CONFIG: /* 请求系统配置 */
						{   //请求系统配置
							printf("......REQ_SYSTEM_CONFIG.......\n");
							GetConfig(pReq, &pResp);//送入参数
							break;
                        
						}		
						case SET_SYSTEM_CONFIG:
						{
							printf("......SET_SYSTEM_CONFIG.......\n");
							SetConfig(pReq, &pResp);
							break;
						}
						default:
						{
                           LOGD(" cmd [default[%x]]\n", pReq->m_pIpHdr->dvrip_cmd);
						}
	            		
	            		break;
			}
		
			 if ( pResp)   //接收了到数据，解包到msghdr中发送
	        {
	        	
	            msghdr_t msghdr;
	            memset(&msghdr, 0, sizeof(msghdr));
	            msghdr.buf     = (void*)pResp->m_pBuffer;
	            msghdr.buf_len = pResp->m_iTotalLen;
	            DvrNetSendMsg(pConnect, &msghdr);
				SIVnPdu_Destory(&pResp);
				//LOGD("22222222222222222222222222222222\n");

	        }

		}

		SIVnPdu_Destory(&pReq);
		
	return 2;
}




/*
 *函数说明：登录消息返回包处理
 */
int RegQuest(struct conn *pConnect,struct SIVnPdu* pReqPDU,struct SIVnPdu** pRespPDU)
{

	if(pReqPDU==NULL)return -1; 
	struct SIVnPdu *pRspPdu; 
	SIVnPdu_Init(&pRspPdu);
	if(!pRspPdu)return -1;
	pRspPdu->m_iTotalLen=0;
	pRspPdu->m_pIpHdr->dvrip_cmd = ACK_USER_LOGIN;
    pRspPdu->m_pIpHdr->dvrip_r0 = 0;
    pRspPdu->m_pIpHdr->dvrip_r1 = pReqPDU->m_pIpHdr->dvrip_r1;
    pRspPdu->m_pIpHdr->dvrip_p[0] = EnLoginResult_Succeeded;
    pRspPdu->m_pIpHdr->dvrip_p[2] = 1;//g_nCapture
    pRspPdu->m_pIpHdr->dvrip_p[3] = 9; // 新的码流H264
    pRspPdu->m_pIpHdr->dvrip_p[4] = 11; //DVR_NVS_C
	memcpy(pRspPdu->m_pIpHdr->dvrip_p + 8,(char *)&pConnect->ulConnSequenceFlag ,sizeof(unsigned long ));
	pRspPdu->m_pIpHdr->dvrip_p[16] = 6;
    pRspPdu->m_pIpHdr->dvrip_p[17] = 0;
    pRspPdu->m_pIpHdr->dvrip_p[18] = ~(pRspPdu->m_pIpHdr->dvrip_p[16]);
	pRspPdu->m_pIpHdr->dvrip_p[19] = 0;
    pRspPdu->m_pIpHdr->dvrip_p[20] = 0x07;
    pRspPdu->m_pIpHdr->dvrip_p[21] = 1; 		
    pRspPdu->m_pIpHdr->dvrip_p[22] = 0x64;	
    pRspPdu->m_pIpHdr->dvrip_p[23] = 0x02; 		
    bool bIsSuccess =1;
	 if(pReqPDU->m_pIpHdr->dvrip_v < DVRIP_VERSION)
    {
        pConnect->iClientFlag = 0;
        LOGD("old client verison %d \n",pReqPDU->m_pIpHdr->dvrip_v);
    }
    else
    {
        pConnect->iClientFlag = 1;
        LOGD("net  client verison %d \n",pReqPDU->m_pIpHdr->dvrip_v);
    }

    if(bIsSuccess)//链接直接成功，不失败
	{
		pRspPdu->m_pIpHdr->dvrip_p[0] = EnLoginResult_Succeeded;
        pRspPdu->m_pIpHdr->dvrip_p[1] = 2;        //统一设置为管理员
         if( pReqPDU->m_pIpHdr->dvrip_r1 & BITMSK(0) )
        {


			STlv tlv_sys_attr;
			STlv_Init(&tlv_sys_attr);
			SYSATTR_EX_T* pSysattr=(SYSATTR_EX_T *)malloc(sizeof(SYSATTR_EX_T));
			memset(pSysattr,0,sizeof(SYSATTR_EX_T));
			Net_GetSysAttrEx(pSysattr);
        	tlv_sys_attr.m_type=DEV_SYSTEM_INFO_DEV_ATTR;
			STlv_Set(&tlv_sys_attr,(unsigned char*)pSysattr, sizeof(SYSATTR_EX_T), false);
			free(pSysattr);
			
			char seq[48] = {0};  //没有序列号的接口
			//SystemGetSerialNumber(seq,sizeof(seq));//还没有接口暂时不使用
			STlv tlv_seq;
			STlv_Init(&tlv_seq);

			tlv_seq.m_type=DEV_SYSTEM_INFO_DEV_ID;
			
		
			char version[64] ="IPD_1.2.S30.OV9732.R";
			char pubdate[32] = {0};
			Net_SYSTEM_TIME tm;
	        Net_Version_GetBuildDate(&tm); 		  //获取时间
	        Net_FormatTimeString(&tm,pubdate,0);  //将时间转成字符串
	        sprintf(version+strlen(version), "Build: %s", pubdate);
	        
			STlv tlv_version;
			STlv_Init(&tlv_version);
			tlv_version.m_type=DEV_SYSTEM_INFO_DEV_VER;
			STlv_Set(&tlv_version,(unsigned char*)version, sizeof(version), false);
			
			USER_AUTH_LIST auth;
			Net_GetUserAuth(&auth);
			STlv tlv_auth;
			STlv_Init(&tlv_auth);
			tlv_auth.m_type=DEV_SYSTEM_INFO_USER_AUTH;
			STlv_Set(&tlv_auth,(unsigned char*)&auth, sizeof(USER_AUTH_LIST), false);
			int DevType;                        
        	DevType=101;  //没有接口先写死
        	
        	STlv tlv_driver_type;
			STlv_Init(&tlv_driver_type);
			tlv_driver_type.m_type=DEV_SYSTEM_INFO_DEV_TYPE;
			STlv_Set(&tlv_driver_type,(unsigned char*)&DevType, sizeof(DevType),false);
			int ext_len = tlv_sys_attr.m_len+8
                    			+tlv_seq.m_len+8
                    			+tlv_auth.m_len+8;
            SPacket* pAllPacket=(SPacket*)malloc(sizeof(SPacket));
            if(pAllPacket==NULL)
            {
			LOGE("The pAllPacket malloc error \n");
            }
            pAllPacket->m_Length=0;
            pAllPacket->m_pBuffer=(unsigned char*)malloc(ext_len+200);
            if(pAllPacket->m_pBuffer==NULL)
            {
	            while(1)
	            {
				LOGE("The pAllPacket->m_pBuffer malloc error \n");
				}
            }
            memset(pAllPacket->m_pBuffer,0,ext_len+200);
    
			unsigned char* p = NULL;
			int tmp_len = 0;
			STlv_Pack(&tlv_sys_attr,&p,&tmp_len);
			SPacket_PutBuffer(pAllPacket,p, tmp_len);	

			STlv_Set(&tlv_seq,(unsigned char*)seq, sizeof(seq), false);
			STlv_Pack(&tlv_seq,&p,&tmp_len);
			SPacket_PutBuffer(pAllPacket,p, tmp_len);		
			
			STlv_Pack(&tlv_version,&p,&tmp_len);
			SPacket_PutBuffer(pAllPacket,p, tmp_len);
			
			//STlv_Pack(&tlv_auth,&p,&tmp_len);
			//SPacket_PutBuffer(pAllPacket,p, tmp_len);
			
			STlv_Pack(&tlv_driver_type,&p,&tmp_len);
			SPacket_PutBuffer(pAllPacket,p,tmp_len);
		
			Net_packetBody(pRspPdu,(char*)pAllPacket->m_pBuffer, pAllPacket->m_Length);
	
			//使用的memcpy直接释放，没问题
			SPacket_Destory(&pAllPacket);
	        free(tlv_version.m_pBuffer);
	        free(tlv_seq.m_pBuffer);
	        free(tlv_sys_attr.m_pBuffer);
	        free(tlv_driver_type.m_pBuffer);


        }
         else
        {	
        	Net_packetBody(pRspPdu,NULL,0);
        }
	}
	pRspPdu->m_pIpHdr->dvrip_v  = pReqPDU->m_pIpHdr->dvrip_v; 
    *pRespPDU = pRspPdu; //在外面释放
	return 0;
}











